package com.schedule.course.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.schedule.common.CommonResult;
import com.schedule.course.entity.Course;
import com.schedule.course.entity.CourseParam;
import com.schedule.course.service.CourseService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/api/course")
public class CourseController {
    @Autowired
    private CourseService courseService;


    /**
     * 新增课程
     * @param course
     * @return
     */
    @PostMapping
    public CommonResult<String> add(@RequestBody Course course) {
        course.setCourseTime(new Date());
        boolean save = courseService.save(course);
        if(save){
            return CommonResult.success("新增成功!");
        }
        return CommonResult.error("新增失败!");
    }


    /**
     * 编辑课程
     * @param course
     * @return
     */
    @PutMapping
    public CommonResult<String> edit(@RequestBody Course course) {
        course.setCourseTime(new Date());
        boolean save = courseService.updateById(course);
        if(save){
            return CommonResult.success("编辑成功!");
        }
        return CommonResult.error("编辑失败!");
    }


    /**
     * 删除
     * @param courseId
     * @return
     */
    @DeleteMapping("/{courseId}")
    public CommonResult<String> delete(@PathVariable("courseId") Long courseId){
        boolean save = courseService.removeById(courseId);
        if(save){
            return CommonResult.success("删除成功!");
        }
        return CommonResult.error("删除失败!");
    }


    /**
     * 查询列表
     * @param courseParam
     * @return
     */
    @GetMapping("/list")
    public CommonResult<IPage<Course>> getList(CourseParam courseParam){
        //构造分页对象
        IPage<Course> page = new Page<>();
        page.setCurrent(courseParam.getCurrentPage());
        page.setSize(courseParam.getPageSize());
        //构造查询条件
        QueryWrapper<Course> query = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(courseParam.getCourseName())){
            query.lambda().like(Course::getCourseName,courseParam.getCourseName());
        }
        if(StringUtils.isNotEmpty(courseParam.getCourseType())){
            query.lambda().eq(Course::getCourseType,courseParam.getCourseType());
        }
        //查询
        IPage<Course> list = courseService.page(page, query);
        return CommonResult.success("查询成功",list);
    }
}
